<script setup>
import { useMessage, NButton, NIcon, darkTheme, NModal, NCard, NInput, NInputGroup, NUpload, NSpin, NDatePicker } from 'naive-ui'
import PostAdd from '@/components/icons/PostAdd.vue'
import { useStore } from '@/stores/index'
import axios from 'axios'
import { ref } from 'vue'
import { useRouter } from 'vue-router';

const router = useRouter()  // 路由实例
const message = useMessage() // 实例化信息条
const backedHost = useStore().$state.backedHost // 后端API前缀
const token = localStorage.getItem('token')  // 用户token

const showLoading = ref(false)  // 是否显示loading
const uploadBtn = ref(true)  // 是否禁用上传按钮
const showUploadPostModal = ref(false)  // 是否显示上传文章弹窗
const uploadImageObj = ref({})  // 当前文件上传ID对应的后端图片ID
// 上传文章信息
const uploadPostInfo = ref({
    title: '',
    content: '',
    image_ids: '',
    create_timestamp: new Date().getTime()  // 上传时间戳
})

// 删除上传的图片
function deleteImage(fileData) {
  uploadBtn.value = false  // 禁用编辑按钮
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + token },
    url: backedHost + '/image/delete_image?id=' + uploadImageObj.value[fileData.file.id]
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('删除成功！')
      }
      uploadBtn.value = true  // 启用编辑按钮
    })
    .catch((error) => {
      console.log(error)
      message.error(error.response.data.message)
      uploadBtn.value = true  // 启用编辑按钮
    })  
}

// 上传文章
function uploadPost() {        
    if (uploadPostInfo.value.title === '') {
        message.warning('请填写标题！')
        return false
    }
    // 将图片ID列表转换为字符串
    uploadPostInfo.value.image_ids = Object.values(uploadImageObj.value).join(',')
    const fetchConfig = {
        method: 'post',
        headers: { Authorization: 'Bearer ' + token },
        url: backedHost + '/post/add',
        data: uploadPostInfo.value
    }
    uploadBtn.value = false  // 禁用编辑按钮
    showLoading.value = true
    axios(fetchConfig)
        .then((response) => {
            if (response.data.code === 2000) {
                message.success('上传成功！')
                showLoading.value = false
                showUploadPostModal.value = false  // 关闭编辑弹窗
                toIndex()
            }
            uploadBtn.value = true  // 启用编辑按钮
        })
        .catch((error) => {
            console.log(error)
            message.error(error.response.data.message)
            showLoading.value = false
            uploadBtn.value = true  // 启用编辑按钮
        })
}

// 返回首页
function toIndex() {
    if (window.location.pathname === '/index') {
        router.push('/')
    } else if (window.location.pathname === '/') {
        router.push('/index')
    }
    // 将修改过的图片数据置空
    uploadImageObj.value = {}
}
</script>

<template>
    <div>
        <n-button id="add-post-btn" color="aqua" round size="medium" style="width: 50%;" @click="showUploadPostModal = true">
            <template #icon>
                <n-icon class="icon-btn" size="25"><PostAdd /></n-icon>
            </template>
        </n-button>
        <!-- 上传文章弹窗 -->
        <n-modal v-model:show="showUploadPostModal" :mask-closable="false">
            <n-spin :show="showLoading" :theme="darkTheme" style="width: 90%">
                <n-card :theme="darkTheme" title="上传文章" :bordered="false" size="huge" role="dialog" aria-modal="true">
                    <!-- 文章标题 -->
                    <n-input-group>
                        <n-button color="#F6F5F5" ghost>标题</n-button>
                        <n-input v-model:value="uploadPostInfo.title" type="text" placeholder="请输入标题（必填）" :theme="darkTheme" clearable/>
                    </n-input-group>
                    <!-- 日期选择 -->
                    <div class="post-action-group">
                    <n-input-group>
                        <n-button color="#F6F5F5" ghost>日期</n-button>
                        <n-date-picker input-readonly v-model:value="uploadPostInfo.create_timestamp" type="datetime" clearable style="width: 100%;"/>
                    </n-input-group>
                    </div>
                    <!-- 文章内容 -->
                    <div class="post-action-group">
                        内容：
                        <n-input v-model:value="uploadPostInfo.content" type="textarea" placeholder="请输入内容" :theme="darkTheme" clearable/>
                    </div>
                    <!-- 图片上传 -->
                    <div class="post-action-group">
                        <n-upload
                            accept="image/*"
                            :theme="darkTheme"
                            :action="backedHost + '/image/upload_image'"
                            list-type="image-card"
                            name="image"
                            :headers="{Authorization: 'Bearer ' + token}"
                            @remove="deleteImage"
                            @before-upload="(_) => {uploadBtn = false}"
                            @error="(_) => {uploadBtn = true;message.error('上传失败，请重试！')}"
                            @finish="(fileData) => {uploadBtn = true;uploadImageObj[fileData.file.id] = JSON.parse(fileData.event.currentTarget.response).data.id;message.success('上传成功！')}"
                        >
                            上传新图
                        </n-upload>
                    </div>
                    <!-- 修改按钮 -->
                    <template #footer>
                        <n-button color="#52D3D8" :theme="darkTheme" style="width: 100%;" :disabled="!uploadBtn" @click="uploadPost()">提交</n-button>          
                        <n-button color="#d4237a" :theme="darkTheme" style="width: 100%;margin-top: 10px;" :disabled="!uploadBtn" @click="showUploadPostModal = false">取消</n-button>
                    </template>
                </n-card>
            </n-spin>            
        </n-modal>                    
    </div>
</template>

<style>
.post-action-group {
  margin-top: 10px;
}
#add-post-btn {
    background: linear-gradient(90deg,#03a9f4,#f441a5,#ffeb3b,#03a9f4);
    background-size: 400%;
    line-height: 100%;
    text-align: center;
    color: #fff;
    /* 设置成胶囊状 */
    border-radius: 50px;
}
/* 设置发光 */
#add-post-btn::before{
    content: "";
    position: absolute;
    left: -5px;
    right: -5px;
    top: -5px;
    bottom: -5px;
    background: linear-gradient(90deg,#03a9f4,#f441a5,#ffeb3b,#03a9f4);
    background-size: 400%;
    border-radius: 50px;
    filter: blur(20px);
    z-index: -1;
}
#add-post-btn:hover::before{
    animation: sun 4s infinite;
}
#add-post-btn:hover{
    animation: sun 4s infinite;
}
/* 设置流光 */
@keyframes sun{
    100%{
        background-position: -400% 0;
    }
}
</style>